<template>
  <el-dialog v-loading="loading" title="分配权限" :visible.sync="showPermDialog" @close="btnPermCancel">
    <!-- 权限是一颗树 -->
    <!-- 将数据绑定到组件上 -->
    <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
    <!-- id作为唯一标识 -->
    <el-tree ref="permTree" :data="treeList" :props="defaultProps" show-checkbox check-strictly default-expand-all node-key="id" :default-checked-keys="selectCheck" />
    <!-- 确定 取消 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
        <el-button size="small" @click="btnPermCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleDetail, assignPrem } from '@/api/role'
export default {
  data() {
    return {
      loading: false,
      showPermDialog: false,
      // 权限的属性数据
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 原来默认选中的权限ids的集合
      selectCheck: [],
      // 角色id
      id: ''
    }
  },
  methods: {
    // 获取权限列表树
    async getPermissionList() {
      this.loading = true
      const list = await getPermissionList()
      // 查询数据并转换为树形表格要求的树形数据
      this.treeList = tranListToTreeData(list, '0')
      this.loading = false
    },
    // 获取角色详情中该角色原有的权限列表数据
    async getRolePermIds() {
      const { permIds } = await getRoleDetail(this.id)
      this.selectCheck = permIds
    },

    // 打开对话框
    async open(roleId) {
      this.id = roleId
      // 获取权限列表数据
      await this.getPermissionList()
      // 获取角色原有的权限
      await this.getRolePermIds()
      this.showPermDialog = true
    },
    btnPermCancel() {
      this.selectCheck = []
      this.showPermDialog = false
    },
    async btnPermOK() {
      // 获取选中的节点数组
      const perIds = this.$refs.permTree.getCheckedKeys()
      await assignPrem({ id: this.id, permIds: perIds })
      this.$message.success('分配权限成功')
      this.showPermDialog = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
